var urlApi = "http://japenagosc.dyndns.org:1220/wiki/api.php";

var targetArticleName;
var sourceArticleName;

// Raw data and Metadata
var $sourceArticleSectionsMetadata;
var sourceArticleContent;

var $targetArticleSectionsMetadata;
var targetArticleContent;

// Sections
var sourceSectionsContent = new Array();
var sourceSectionsLevel = new Array();
var sourceSectionsIndex = new Array();
var sourceSectionsParent = new Array(); // To help creating the 'parent' tree in Processing'

//Sections
var targetSectionsContent = new Array();
var targetSectionsLevel = new Array();
var targetSectionsIndex = new Array();
var targetSectionsParent = new Array(); // To help creating the 'parent' tree in Processing'

// Levels
var sourceLevels = new Array();
var targetLevels = new Array();

// Sections to transclude
var contentOfSectionsToTransclude = new Array(); // Content of the NEW transcluded sections (to save in target article)
var targetIndexOfSectionsToTransclude = new Array(); // Index of target section to add new transcluded section AFTER
var sourceIndexOfSectionsToTransclude = new Array(); // Index of source section to edit and add the <transclusion> tag
var indexesOfNewTransclusions = new Array(); // Indexes of the "new" unregistrered transclusions. These have to be updated in the DB later
var levelOfSourceSections = new Array(); //
var ordenSources = new Array(); // usado para organizar de mayor a menor el orden de ejecución y de registro de las transclusiones segun sIndex

var flagTooltip = false;

$(document).ready(function(){
  targetArticleName = $("#trTarget").val();
  sourceArticleName = $("#trSource").val();

  // The visuals are loaded
  initLoadingDiv();

  // The articles are loaded in the arrays
  //loadArticles();

  $("#previewSectionText").hide();
  $(document).mousemove(showPreviewText);

  $("#divCanvas").css({
	  "width":"800px",
	  "position":"absolute",
	  "bottom":"60px",
	  "left":"100px"
  });

  $("#botonGuardarCambios").css({
	  "width":"200px",
	  "position":"absolute",
	  "bottom":"20px",
	  "left":"400px"
  }).click(saveChanges);  
});

function showPreviewText(event){
  $("#previewSectionText").css({
    "position" : "absolute",
    "top" : event.pageY,
    "left" : event.pageX,

    "max-width" : "200px",
    "max-height" : "150px",

    "background-color" : "#FFF",
    "text-align" : "justify",
    "text-color" : "#000",
    "font-size" : "11px",
    "margin" : "10px",
    "padding" : "10px",

    "text-overflow" : "ellipsis",
    "white-space" : "normal",
    "overflow" : "hidden",
    "z-index":"9999"
  });  
  
  if(flagTooltip){
    // FIRST: Format the text of the preview div
    
    $("#previewSectionText").show();
  } 
  else{
    $("#previewSectionText").hide();
  }
}

function loadArticles(){
  // Target Article
  $.ajax({
    url: urlApi,

    data:{
	action:'parse',
	format:'xml',

	page:targetArticleName,
	prop:'sections|wikitext'
    },

    dataType: 'xml',

    success: function(data){
	// The data is parsed into two variables
	$targetArticleSectionsMetadata = $( data );
	targetArticleContent = $( data ).find('wikitext').text();

	// It is initialized
	initArticleContents('TARGET');

        $("#pSketch").ready(function(){
            var pjs = Processing.getInstanceById('pSketch');
            pjs.loadArticleSketch("TARGET");
        });
	      
    }
  });

  // Source Article
  $.ajax({
    url: urlApi,

    data:{
	action:'parse',
	format:'xml',

	page:sourceArticleName,
	prop:'sections|wikitext'
    },

    dataType: 'xml',

    success: function(data){
	// The data is parsed into two variables
	$sourceArticleSectionsMetadata = $( data );
	sourceArticleContent = $( data ).find('wikitext').text();

	// It is initialized
	initArticleContents('SOURCE');

        $("#pSketch").ready(function(){
            var pjs = Processing.getInstanceById('pSketch');
            pjs.loadArticleSketch("SOURCE");
        });

        
    }
  });
}

function initArticleContents(articleType){
  // articleType = 'SOURCE' or 'TARGET'

  // Local variable
	var localLevels = new Array();
	var $tempArticleSectionsMetadata, tempLevels, tempSectionsLevel, tempSectionsIndex, tempSectionsContent, tempArticleContent, tempSectionsParent;

	if(articleType == 'SOURCE'){
		$tempArticleSectionsMetadata = $sourceArticleSectionsMetadata;
		tempLevels = sourceLevels;

		tempSectionsLevel = sourceSectionsLevel;
		tempSectionsIndex = sourceSectionsIndex; 
		tempSectionsContent = sourceSectionsContent;
        tempSectionsParent = sourceSectionsParent;

		tempArticleContent = sourceArticleContent;
	}
	else{
		$tempArticleSectionsMetadata = $targetArticleSectionsMetadata;
		tempLevels = targetLevels;

		tempSectionsLevel = targetSectionsLevel;
		tempSectionsIndex = targetSectionsIndex;
		tempSectionsContent = targetSectionsContent;
        tempSectionsParent = targetSectionsParent;

		tempArticleContent = targetArticleContent;
	}

	var j=0; 
	$tempArticleSectionsMetadata.find( "s" ).each(function(){
		$tempValue = $(this);

		// Loads the values of leveling
		$tempArticleSectionsMetadata.find( "s" ).each(function(){
			$tempValue2 = $(this);

			if( localLevels[ $(this).attr('level') ] != 'x'){ // If not added
				tempLevels[j] = $tempValue2.attr("level");
				j++;

				localLevels[ $(this).attr('level') ] = 'x';
			}
		});
	});

	allSectionsJQuery = new Array();
	$tempArticleSectionsMetadata.find( "s" ).each( function( index , value ){
		allSectionsJQuery[index] = value;
	});

	numberOfSections = allSectionsJQuery.length;
	for (i=0; i<numberOfSections; i++){
		j=i+1;
		if(j == numberOfSections ){
			// Llego al fin
			reachedLastElement = true;
		}
		else{
			reachedLastElement = false;
		}

		while( $(allSectionsJQuery[i]).attr('level') < $(allSectionsJQuery[j]).attr('level') && !reachedLastElement ){
			j++;

			if(j == numberOfSections ){
				// Llego al fin
				reachedLastElement = true;
			}
		}

		// Informacion que ya tenemos
		tempSectionsLevel[i] = $(allSectionsJQuery[i]).attr('level');
		tempSectionsIndex[i] = $(allSectionsJQuery[i]).attr('index');

		sectionOffset = $(allSectionsJQuery[i]).attr('byteoffset');
		// Se extrae la información requerida
		if(reachedLastElement){
			// Si llego hasta el final se hace un substring de lo que queda
			tempSectionsContent[i] = tempArticleContent.substring( sectionOffset );
		}
		else{
			nextOffset = $(allSectionsJQuery[j]).attr('byteoffset');
			tempSectionsContent[i] = tempArticleContent.substring( sectionOffset, nextOffset );
		}
                
                // TODO: Modificar el texto del div de preview. Será totalmente necesario?
                modifyTextOfSection( tempSectionsContent[i], i );
	}
          
	// The parent section for each section element
	for( i=0; i<tempSectionsLevel.length; i++ ){
		k=i;

		while ( (tempSectionsLevel[i] <= tempSectionsLevel[k]) && (k>0) ){
			k--;
		} 
		if (tempSectionsLevel[i] == tempLevels[0]){ // a 'root' section
			tempSectionsParent[i] = -1; 
		}
		else{ 
			tempSectionsParent[i] = k;
		} 
	}
        
} 

// Function that 'formats' (let's see if it's applicable) the section content to display it correctly into the div
function modifyTextOfSection ( sectionContent, i ){ 
    
}

function previewText(sectionContent){
  if(sectionContent == ''){
    flagTooltip = false;

    // Trigger the event
    $(document).mousemove();
  }
  else{
    if(sectionContent.length > 5000){
	sectionContent = sectionContent.substr(0,5000);
    }

    $("#previewSectionText").html(sectionContent);

    flagTooltip = true;

    // Trigger the event
    $(document).mousemove();
  }
}

function showTooltip(textToShow){
    $("#additionalTooltip").css({
    "background-color" : "#FFF",
    "text-align" : "center",
    "text-color" : "#F00",
    "font-size" : "16px"
  });

  $("#additionalTooltip").html(textToShow); 
 
  if(textToShow == ""){
      $("#additionalTooltip").hide();
  }
  else{
      $("#additionalTooltip").show();
  }
}

function initLoadingDiv(){
  $("#loadingDiv").hide();

  $("#loadingDiv").css({
    "position" : "absolute",
    "bottom" : "5px",
    "right" : "5px"
  });

  $("#loadingDiv").ajaxStart(function(){
    $(this).show();
  });

  $("#loadingDiv").ajaxStop(function(){
    $(this).hide();
  });
}	

function registerNewTranscludedSection(targetIndex, sourceIndex, levelSourceTr){
	contentOfSectionsToTransclude.push(""); // {{#transcludeid: articleName|trid}}
	targetIndexOfSectionsToTransclude.push(targetIndex); // API index
	sourceIndexOfSectionsToTransclude.push(sourceIndex); // API index
	indexesOfNewTransclusions.push(getNewTrid());  
	levelOfSourceSections.push(levelSourceTr); 

	ordenarSources();
}
 
function ordenarSources (){ 
	copiaSources = Array(sourceIndexOfSectionsToTransclude.length);
	for(i=0; i<sourceIndexOfSectionsToTransclude.length; i++){
		copiaSources[i] = sourceIndexOfSectionsToTransclude[i];
	}

	ordenSources = new Array(copiaSources.length);
	for(j = 0; j < ordenSources.length; j++){
		ordenSources[j] = j;
	}

	for(k = 0; k < copiaSources.length - 1; k++){
		for (m = k+1; m < copiaSources.length; m++){
			if(copiaSources[m-1] > copiaSources[m]){
				temp = copiaSources[m-1];
				copiaSources[m-1] = copiaSources[m];
				copiaSources[m] = temp;

				temp = ordenSources[m-1];
				ordenSources[m-1] = ordenSources[m];
				ordenSources[m] = temp;
			}
		}
	}
}

function saveChanges(){
  /*
   * Function that saves the changes made to the target article
   */

  $.ajax({
    url: urlApi, // first, the token acquisition

    data:{
	action:'query',
	format:'xml',

	prop:'info',
	intoken:'edit',
	titles:targetArticleName + "|" + sourceArticleName
    },

    dataType: 'xml',

    success: function(data){
		eToken = $( data ).find('page').attr('edittoken');

		$.each(ordenSources, function(index, value) {
			$("#divGuardarCambios").append("<span id='" + indexesOfNewTransclusions[value] + "'>Transclusion from <b>" + sourceArticleName + "</b> to <b>" + targetArticleName + "</b>, section <b>" + sourceIndexOfSectionsToTransclude[value] +  "</b>: </span><br/>");

			eTargetContent = "";
			$.each(targetSectionsIndex, function(eTIndex, eTValue){
				if(eTValue == targetIndexOfSectionsToTransclude[value] ){
					eTargetContent = targetSectionsContent[eTIndex];
				}
			});

			eSourceContent = "";
			$.each(sourceSectionsIndex, function(eSIndex, eSValue){
				if(eSValue == sourceIndexOfSectionsToTransclude[value] ){
					eSourceContent = sourceSectionsContent[eSIndex];
				}
			});

			targetTemp = $.trim(eTargetContent) + "\n{{#transcludeid: " + sourceArticleName + "|" + indexesOfNewTransclusions[value] + "}}";

			//Target article
			$.ajaxq("targetsqueue", {
				url: urlApi,

				data:{
				action:'edit',

				title:targetArticleName,

				section:targetIndexOfSectionsToTransclude[value],

				text:targetTemp,

				token:eToken
				},

				type:'post',

				cache:'false',

				success: function(data){
					$("#" + indexesOfNewTransclusions[value]).append(" [Target updated] ");
				}
			});

			// Database
			$.ajaxq("dbqueue",{
				url: "../php/registerTransclusionInDB.php",

				data:{
					trid:indexesOfNewTransclusions[value],

					source:sourceArticleName,

					target:targetArticleName,

					sectionId:sourceIndexOfSectionsToTransclude[value],

					trtext:""
				},

				type:'post',

				cache:'false',

				success: function(data){
					$("#" + indexesOfNewTransclusions[value]).append(" [DB updated] ");
				}
			});
	
			nroIguales = 2 * levelOfSourceSections[value]; 
			indiceTitulo = 0;

			while(nroIguales > 0){
				if( eSourceContent.charAt(indiceTitulo) == '=' ){
					nroIguales--;
				}
				indiceTitulo++;
			}

			sourceTemp = eSourceContent.substr( 0 , indiceTitulo ) + "\n<transclusionid-" + indexesOfNewTransclusions[value] + ">\n" +  $.trim(eSourceContent.substr(indiceTitulo)) + "\n</transclusionid-" + indexesOfNewTransclusions[value] + ">";
			$.ajaxq("sourcesqueue", {
				url: urlApi,

				data:{
				action:'edit',

				title:sourceArticleName,

				section:sourceIndexOfSectionsToTransclude[value],

				text:sourceTemp,

				token:eToken
				},

				type:'post',

				cache:'false',

				success: function(data){
					$("#" + indexesOfNewTransclusions[value]).append(" [Source updated] ");
				}
			});

		});
    }
  });
}

function getRandomNumber(lowerBound,upperBound){
	aleatorio = Math.floor(Math.random() * (upperBound - lowerBound)) + lowerBound;
	return aleatorio;
}

function getRandomChar() {
	var numberChars = "0123456789";
	var lowerChars = "abcdefghijklmnopqrstuvwxyz";
	//var upperChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

	var charSet = "";

	charSet += numberChars;
	charSet += lowerChars;
	//charSet += upperChars;

	caracter = charSet.charAt(getRandomNumber(0, charSet.length));

	return caracter;
}

function getNewTrid(){
	var newTrid = "";

	var i = 5;

	while( i > 0 ){
		newTrid = newTrid + getRandomChar();
		i--;
	}

	return newTrid;
}